﻿using Microsoft.Extensions.Logging;
using Sgr.Domain.Uow;

namespace Sgr.BackGroundTasks
{
    /// <summary>
    /// 清理数据的后台任务
    /// </summary>
    public class CleanupBackgroundTask : IBackGroundTask
    {
        private readonly IEnumerable<ICleanupHandle> _handlers;
        private readonly ILogger<CleanupBackgroundTask> _logger;

        public CleanupBackgroundTask(
            IEnumerable<ICleanupHandle> handlers,
            ILogger<CleanupBackgroundTask> logger)
        {
            _handlers = handlers;
            _logger = logger;
        }

        public async Task ExecuteAsync(CancellationToken cancellationToken = default)
        {
            _logger.LogInformation($"CleanupBackgroundTask 于 {DateTime.UtcNow} 开始清理资源");

            foreach (var handler in _handlers)
            {
                try
                {
                    await handler.CleanupAsync(cancellationToken);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, $"CleanupBackgroundTask 执行清理时，处理器 {handler.GetType().FullName} 发生错误。");
                }
            }

            _logger.LogInformation($"CleanupBackgroundTask 清理任务完成。");
        }
    }
}